package com.ptmall.app.ui.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jauker.widget.BadgeView;
import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.bean.CategoryBean;
import com.ptmall.app.bean.PageData;
import com.ptmall.app.bean.ProductBean;
import com.ptmall.app.bean.ShopCarBean;
import com.ptmall.app.bean.StyleBean;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.ui.adapter.CateListAdapter;
import com.ptmall.app.ui.adapter.GoodListAdapter;
import com.ptmall.app.ui.adapter.GoodListAdapter2;
import com.ptmall.app.view.PullToRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CateListActivity extends BaseMvpActivity implements View.OnClickListener {

    String id;

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    GridView goodlist;
    ListView catelist;

    CateListAdapter mCateListAdapter;
    GoodListAdapter2 mGoodListAdapter;
    TextView tv_search, tv_zonghe, tv_jiage, tv_youhui, tv_shaixuan;

    Intent intent;
    int page = 1;
    String ids;
    List<ProductBean> mDataLists = new ArrayList<>();

    private PullToRefreshLayout ptrl;

    RelativeLayout rl;
    private PathMeasure mPathMeasure;
    private float[] mCurrentPosition = new float[2];

    RelativeLayout rel;

    public BadgeView mBadgeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_goodlist);
    }

    @Override
    public void initViews() {
        id = getIntent().getStringExtra("id");
        ptrl = (PullToRefreshLayout) findViewById(R.id.refresh_views);
        goodlist = (GridView) findViewById(R.id.goodlist);
        catelist = (ListView) findViewById(R.id.catelist);
        tv_zonghe = (TextView) findViewById(R.id.zonghe);
        tv_jiage = (TextView) findViewById(R.id.jiage);
        tv_youhui = (TextView) findViewById(R.id.youhui);
        tv_shaixuan = (TextView) findViewById(R.id.shaixuan);
        tv_search = (TextView) findViewById(R.id.search);
        rl = (RelativeLayout) findViewById(R.id.rl);
        rel = (RelativeLayout) findViewById(R.id.rel);
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mBadgeView = new BadgeView(this);
        mBadgeView.setBackground(10, 0xFFFF0000);//色
        mBadgeView.setTargetView(rel);
    }

    @Override
    public void initEvents() {
        findViewById(R.id.tocar).setOnClickListener(this);
        mCateListAdapter = new CateListAdapter(getContext(), null);
        catelist.setAdapter(mCateListAdapter);
        mGoodListAdapter = new GoodListAdapter2(getContext(), null);
        goodlist.setAdapter(mGoodListAdapter);
        mGoodListAdapter.setClickInterface(new GoodListAdapter2.ClickInterface() {
            @Override
            public void shopcaradd(ImageView iv, String id, int position) {
                addcar(id, "1",iv);

            }

        });
//        getdata(id);
//        getCate();
        getstyle2();
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent = new Intent(getContext(), SeachActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        ptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                page = 1;
                getdata("", "");

            }

            @Override
            public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
                // 加载操作
                page++;
                getdata("", "");

            }
        });
        tv_zonghe.setOnClickListener(this);
        tv_youhui.setOnClickListener(this);
        tv_jiage.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getshopcarNum();
    }

    public void getshopcarNum() {
        apiDataRepository.getShopCarList(null, new ApiNetResponse<PageData<ShopCarBean>>(getContext()) {
            @Override
            public void onSuccess(PageData<ShopCarBean> data) {
                mBadgeView.setText(data.getData().size()+"");
            }
        });
    }
    private void getstyle2() {
        Map<String, String> map = new HashMap<>();
        if (!TextUtils.isEmpty(id)) {
            map.put("styleId", id);
        }
        apiDataRepository.getstyle2(map, new ApiNetResponse<List<CategoryBean>>(getContext()) {
            @Override
            public void onSuccess(List<CategoryBean> data) {
//                for(CategoryBean categoryBean:data){
//                    if(categoryBean.styleId .equals( id)){
//                        categoryBean.select = true;
//                    }
//                }
                data.get(0).select = true;
                ids = data.get(0).styleId;
                getdata("", "");
                mCateListAdapter.pushData(data);
                catelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        for (CategoryBean categoryBean : data) {
                            categoryBean.select = false;
                        }
                        data.get(i).select = true;
                        mCateListAdapter.pushData(data);
                        ids = data.get(i).styleId;
                        mDataLists.clear();
                        page = 1;
                        getdata("", "");
                    }
                });
            }
        });
    }

    private void getdata(String key, String value) {
        Map<String, String> map = new HashMap<>();
        map.put("styleId1", id);
        map.put("styleId2", ids);
        map.put("page", page + "");
        if (!key.equals("")) {
            map.put(key, value);
        }
        apiDataRepository.getGoodList(map, new ApiNetResponse<PageData<ProductBean>>(getContext()) {
            @Override
            public void onSuccess(PageData<ProductBean> data) {
                if (null != ptrl) {
                    ptrl.refreshFinish(PullToRefreshLayout.SUCCEED);
                    ptrl.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if (page == 1) {
                    mDataLists.clear();
                }
                if (null != data.getData() && data.getData().size() > 0) {
                    mDataLists.addAll(data.getData());
                } else {
                }
                mGoodListAdapter.pushData(mDataLists);
            }
        });
    }


    private void getCate() {
        apiDataRepository.getCategory(null, new ApiNetResponse<List<CategoryBean>>() {
            @Override
            public void onSuccess(List<CategoryBean> data) {

            }
        });
    }

    private void addcar(String id, String num,ImageView iv) {
        Map<String, String> map = new HashMap<>();
        map.put("productId", id);
        map.put("num", num);
        apiDataRepository.addShopCar(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("加入购物车成功");
                addCartStart(iv);
                getshopcarNum();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            resetTvColor();
            tv_shaixuan.setTextColor(0xfffaa856);
            getdata("keyword", data.getStringExtra("search"));
        }

    }

    private void resetTvColor() {
        tv_jiage.setTextColor(0xff999999);
        tv_shaixuan.setTextColor(0xff999999);
        tv_youhui.setTextColor(0xff999999);
        tv_zonghe.setTextColor(0xff999999);
    }

    @Override
    public void onClick(View v) {
        resetTvColor();
        switch (v.getId()) {
            case R.id.jiage:
                tv_jiage.setTextColor(0xfffaa856);
                getdata("price_type", "desc");
                break;
            case R.id.youhui:
                tv_youhui.setTextColor(0xfffaa856);
                getdata("youhui", "1");
                break;
            case R.id.zonghe:
                tv_zonghe.setTextColor(0xfffaa856);
                getdata("zonghe", "desc");

                break;
            case R.id.tocar:

                Intent intent = new Intent(getContext(), MainActivity.class);
                intent.putExtra("position", 2);
                startActivity(intent);
                break;
        }
    }


    /**
     * ★★★★★把商品添加到购物车的动画效果★★★★★
     * @param iv
     */
    private void addCartStart( ImageView iv) {
//      一、创造出执行动画的主题---imageview
        //代码new一个imageview，图片资源是上面的imageview的图片
        // (这个图片就是执行动画的图片，从开始位置出发，经过一个抛物线（贝塞尔曲线），移动到购物车里)
        final ImageView goods = new ImageView(getContext());
        goods.setImageDrawable(iv.getDrawable());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
        rl.addView(goods, params);

//        二、计算动画开始/结束点的坐标的准备工作
        //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        int[] parentLocation = new int[2];
        rl.getLocationInWindow(parentLocation);

        //得到商品图片的坐标（用于计算动画开始的坐标）
        int startLoc[] = new int[2];
        iv.getLocationInWindow(startLoc);

        //得到购物车图片的坐标(用于计算动画结束后的坐标)
        int endLoc[] = new int[2];
        endLoc[0] = rl.getWidth()/8*4;
        endLoc[1] = rl.getHeight()+100;
//        car.getLocationInWindow(endLoc);


//        三、正式开始计算动画开始/结束的坐标
        //开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
        float startX = startLoc[0] - parentLocation[0] + iv.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + iv.getHeight() / 2;

        //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
        float toX = endLoc[0] - parentLocation[0];
        float toY = endLoc[1] - parentLocation[1];
        Log.i("location ====","endLoc[]" + endLoc[0] + "  " + endLoc[1]);
        Log.i("location ====","toX[]" + toX + " toY " + toY);
//        四、计算中间动画的插值坐标（贝塞尔曲线）（其实就是用贝塞尔曲线来完成起终点的过程）
        //开始绘制贝塞尔曲线
        Path path = new Path();
        //移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY);
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        //mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，
        // 如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        //★★★属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);
        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // ★★★★★获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
                // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                mPathMeasure.getPosTan(value, mCurrentPosition, null);//mCurrentPosition此时就是中间距离点的坐标值
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });
//      五、 开始执行动画
        valueAnimator.start();

//      六、动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            //当动画结束后：
            @Override
            public void onAnimationEnd(Animator animation) {
                rl.removeView(goods);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

}
